from rest_framework import serializers
from first.models import PurchaseM, PurchaseDetail
from django.http import HttpResponse


class PurchaseMSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=60)
    buyer = serializers.CharField(max_length=12)
    supplier = serializers.CharField(max_length=60)
    call = serializers.CharField(max_length=20)
    time = serializers.DateTimeField()


class MsgSerializer(serializers.Serializer):
    author = serializers.CharField(max_length=20, required=True, label='author')
    title = serializers.CharField(max_length=40, required=True, label='title')
    content = serializers.CharField(max_length=100, required=True, label='content')
    Buildtime = serializers.DateTimeField()


class PurchaseMModelSerial(serializers.ModelSerializer):
    class Meta:
        model = PurchaseM
        fields = '__all__'
        extra_kwargs = {
            'title': {'write_only': False},
            'buyer': {'write_only': False},
            'supplier': {'write_only': False},
            'call': {'write_only': False},
            'time': {'write_only': False},
        }


class PDMSerializer(serializers.ModelSerializer):
    class Meta:
        model = PurchaseDetail
        fields = '__all__'
        depth = 1


class PurchaseMDModelSerial(serializers.ModelSerializer):
    class Meta:
        model = PurchaseDetail
        fields = '__all__'


class PurchaseMDModelSerialDB(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=60)
    buyer = serializers.CharField(max_length=12)
    supplier = serializers.CharField(max_length=60)
    call = serializers.CharField(max_length=20)
    time = serializers.DateTimeField()

    def create(self, validated_data):
        return PurchaseM.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.buyer = validated_data.get('buyer', instance.buyer)
        instance.supplier = validated_data.get('supplier', instance.supplier)
        instance.call = validated_data.get('call', instance.call)
        instance.time = validated_data.get('time', instance.time)
        instance.save()
        return instance

    def get(self, request):
        MM = PurchaseM.objects.all()
        Sdetail = PurchaseMModelSerial(instance=MM, many=True)
        return HttpResponse(Sdetail.data)

    def post(self, request):
        id = request.data.get(id=10)
        dbData = PurchaseM.objects.filter(id=id).first()
        sdata = PurchaseMModelSerial(data=dbData)
        if sdata.is_valid():
            if dbData:
                sdata.update(instance=dbData, data=request.data)
            else:
                sdata.save()
            return HttpResponse(request.data)
        return HttpResponse(sdata.error, status=404)



